<?php 
session_start();
if (!isset($_SESSION['name'])) {
	header("Location: login.php");
}
$db_connect = mysqli_connect("localhost", "root", "", "tractor");

if(isset($_POST['remove'])){
	$id = $_POST['selected'];
	foreach($id as $tractor){
		$removeQuery = "DELETE FROM tractors WHERE tractor_id=$tractor";
		$removed = mysqli_query($db_connect, $removeQuery);
	}
}
if (isset($_POST['buy'])) {
	$name = $_SESSION['name'];
	$id = $_POST['selected'];
	
	$moneyQuery = "select money from users where username = \"$name\"";
	
	$moneyQ = mysqli_query($db_connect, $moneyQuery);
	$moneyArr = mysqli_fetch_assoc($moneyQ);
	$money = $moneyArr['money'];
	
	$total = 0;
	foreach ($id as $tractor) {
		$priceQuery = "select price from tractors where tractor_id = $tractor";
		$priceQ = mysqli_query($db_connect, $priceQuery);
		$priceArr = mysqli_fetch_assoc($priceQ);
		$total += $priceArr['price'];
	}
	
	if ($total <= $money) {
		foreach($id as $tractor){
			$removeQuery = "DELETE FROM tractors WHERE tractor_id=$tractor";
			mysqli_query($db_connect, $removeQuery);
		}
		$currentMoney = $money - $total;
		$alterMoneyQ = "update users set money = $currentMoney where username = $name";
		mysqli_query($db_connect, $alterMoneyQ);
		echo "Congrats you got yourself some useless tractors and have $currentMoney money now";
	}
	else{
		echo "Not enough money sorry";
	}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Awesome tractors</title>
<link rel="stylesheet" type="text/css" href="style/index.css">
</head>
<body>
	<div id="header">
		<img src="images/logo.jpg" alt="logo" id="logo"/>
	</div>
	<form method="post" action="index.php">
	<div id="nav">
		<ul id="navigation">
			<li><button formaction="add.php">Add</button></li>
			<li><input type="submit" name="remove" value="Remove"/></li>
			<li><input type="submit" name="buy" value="Buy"/></li>
		</ul>
	</div>
	<div id="main_section">
		<?php 
		$query = "SELECT tractor_id, name, model, price, link FROM tractors";
		$result = mysqli_query($db_connect, $query);
		
		echo "<table id=\"info\" border=\"1\">";
		
		if(mysqli_num_rows($result) > 0){
			while($row = mysqli_fetch_assoc($result)){
				echo "<tr>";
				echo "<td>" . $row['name'] . "</a></td>";
				echo "<td>" . $row['model'] . "</td>";
				echo "<td>" . $row['price'] . "</td>";
				echo "<td><img src=\"" . $row['link'] . "\" id=\"thumbnail\"/></td>";
				$tractorId = $row['tractor_id'];
				echo "<td><input type=\"checkbox\" name=\"selected[]\" value=\"$tractorId\"/></td>";
				echo "<td><a href=\"edit.php?tractorId=$tractorId\">Edit</a></td>";
				echo "<tr>";
			}
		}			
		?>
	</div>
	</form>
</body>
</html>

<?php 
mysqli_close($db_connect);
?>